using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager : MonoBehaviour
{
    //缓存ui对象的集合
    //private Dictionary<string, GameObject> UIObjects = new Dictionary<string, GameObject>();

    //储存UI层级组
    private Dictionary<string, Transform> UIGroups = new Dictionary<string, Transform>();

    private Transform UIParent;

    private void Awake()
    {
        UIParent = this.transform.parent.Find("UI");
    }

    public void SetUIGroup(List<string> _group)
    {
        for(int i = 0; i < _group.Count; i++)
        {
            GameObject newGroup = new GameObject("Group-" + _group[i]);
            newGroup.transform.SetParent(UIParent, false);

            UIGroups.Add(_group[i], newGroup.transform);
        }
    }

    private Transform GetUIGroup(string _groupName)
    {
        if (!UIGroups.ContainsKey(_groupName))
        {
            Debug.LogError("Group is not exist");
            return null;
        }
        return UIGroups[_groupName];
    }

    public void OpenUI(string _uiName,string _uiGroup, string _luaName)
    {
        GameObject ui = null;

        Transform parent = GetUIGroup(_uiGroup);

        string uiPath = PathUtil.GetUIPath(_uiName);

        Object uiObj = Manager.Pool.Spwan("UI", uiPath);

        //if (UIObjects.TryGetValue(_uiName, out ui))
        //{
        //    UILogic uiLogic = GetComponent<UILogic>();
        //    uiLogic.UIOnOpen();
        //    return;
        //}

        if (uiObj != null)
        {
            ui = uiObj as GameObject;
            UILogic uiLogic = GetComponent<UILogic>();
            uiLogic.UIOnOpen();
            ui.transform.SetParent(parent, false);
            return;
        }

        Manager.Resources.LoadUI(_uiName, (UnityEngine.Object obj) =>
        {
            ui = Instantiate(obj) as GameObject;
            //UIObjects.Add(ui.name, ui);

            Transform uiParent = GetUIGroup(_uiGroup);
            ui.transform.SetParent(uiParent, false);

            UILogic uiLogic = ui.AddComponent<UILogic>();
            uiLogic.assetName = uiPath;
            uiLogic.Init(_luaName);
            uiLogic.UIOnOpen();
        });

    }
}
